package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.mapper.NoticeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class NoticeServiceImpl implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;

    @Override
    public void save(Notice notice) {
        Employee currentUser = UserContext.getCurrentUser();
        notice.setIssuerId(currentUser.getId());
        notice.setPubdate(new Date());
        noticeMapper.insert(notice);
        noticeMapper.insertRelation(notice.getId(), currentUser.getId());
    }

    @Override
    public void delete(Long id) {
        noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Notice notice) {
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public Notice get(Long id) {
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Notice> listAll() {
        return noticeMapper.selectAll();
    }

    @Override
    public PageInfo<Notice> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), "n.pubdate desc"); //对下一句sql进行自动分页
        List<Notice> notices = noticeMapper.selectForList(qo, UserContext.getCurrentUser().getId()); //里面不需要自己写limit
        return new PageInfo<>(notices);
    }

    @Override
    public Notice readNotice(Long noticeId) {
        // 删除之前与通知的关联
        Employee currentUser = UserContext.getCurrentUser();
        noticeMapper.deleteRelation(noticeId, currentUser.getId());
        // 每次读取重新插入
        noticeMapper.insertRelation(noticeId, currentUser.getId());
        // 获取通知具体内容
        Notice notice = noticeMapper.getNoticeContentbyId(noticeId);
        return notice;

    }

}
